package com.simon.mengkou.ui.view;


import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class LoopViewPager extends BaseViewPager {
	private int sleepTime = 5000;
	private static boolean isRunning;
	private boolean autoScroll = true;
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				setCurrentItem(getCurrentItem() + 1, true);
				if (isRunning ) {
					this.sendEmptyMessageDelayed(0, sleepTime);
				}
				break;

			case 1:
				if(isRunning ) {
					this.sendEmptyMessageDelayed(0, sleepTime);
				}
				break;
			}
		}
	};
	
	public LoopViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public LoopViewPager(Context context) {
		super(context);
	}

	@Override
	public void setAdapter(BasePagerAdapter adapter) {
		super.setAdapter(adapter);
		//设置当前展示的位�?
		setCurrentItem(0);
	}
	
	public void setInfinateAdapter(BasePagerAdapter adapter){
		setAdapter(adapter);
	}
	
	public void startScroll() {
		isRunning = true;
		handler.sendEmptyMessageDelayed(0, sleepTime);
	}
	
	public void cancelScroll() {
		isRunning = false;
		handler.removeCallbacksAndMessages(null);
	}

	public void setAutoScroll(boolean enabled) {
		autoScroll = enabled;
	}
	
	@Override
	public void setCurrentItem(int item) {
		item = getOffsetAmount() + (item % getAdapter().getCount());
		super.setCurrentItem(item);
	}
	/**
	 * �?�?��向右(负向滑动)可以滑动的次�?
	 * @return
	 */
	private int getOffsetAmount() {
		if (getAdapter() instanceof LoopViewPagerAdapter) {
			LoopViewPagerAdapter infiniteAdapter = (LoopViewPagerAdapter) getAdapter();
			// 允许向前滚动400000�?
			return infiniteAdapter.getRealCount() * 100000;
		} else {
			return 0;
		}
	}

	private float mDownX;
	private float mDownY;
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		int action = ev.getAction();
		
		switch(action) {
			case MotionEvent.ACTION_DOWN:
				mDownX = ev.getX();
				mDownY = ev.getY();
				getParent().requestDisallowInterceptTouchEvent(true);
				isRunning = false;
				if(autoScroll) {
					handler.removeCallbacksAndMessages(null);
				}
				break;
			case MotionEvent.ACTION_MOVE:
				if(Math.abs(ev.getX() - mDownX) > Math.abs(ev.getY() - mDownY)) {
					getParent().requestDisallowInterceptTouchEvent(true);
				} else {
					getParent().requestDisallowInterceptTouchEvent(false);
				}
				break;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_CANCEL:
				getParent().requestDisallowInterceptTouchEvent(false);	
				isRunning = true;
				if(autoScroll) {
					handler.removeCallbacksAndMessages(null);
					handler.sendEmptyMessage(1);
				}
				break;
		}
		
		return super.dispatchTouchEvent(ev);
	}
	
	

	@Override
	public void setOffscreenPageLimit(int limit) {
		super.setOffscreenPageLimit(limit);
	}
	
	
}
